<?php
/**
 * Created by PhpStorm.
 * User: dt
 * Time: 16:33
 */

namespace  backend\services;

use Yii;
use backend\base\BaseService;
use backend\models\AdminModel;
use backend\models\RoleModel;
use backend\models\DepartmentModel;
use backend\models\PermissionModel;

class RoleService extends BaseService
{
    /**
     * 初始化服务
     * @param string $className
     * @return mixed
     */
    public static function getInstance($className = __CLASS__)
    {
        return parent::getInstance($className);
    }
    
    /*
     * 系统属性列表
     */
    public function getList($data)
    {
        $list = RoleModel::getInstance()->getList($data);
        return $list;
    }

    /*
     * 角色新增
     */
    public function roleAdd($data)
    {
        //新增角色
        $model = new RoleModel(['scenario' => 'add']);
        $info = $model->find()->where(['name' => $data['name']])->one();
        if(empty($info)){
            if ($model->load($data, '') && $model->validate()) {//验证成功
                if ($model->save()) {//保存成功
                    return parent::getData(1,'operate_success_add');
                }
            }
        }else{
            return parent::getData(1,'name_repeat');
        }
        $errorMsg = array_values($model->getErrors());           //报错信息
        return parent::getData(2,$errorMsg[0]);//失败提示
    }

    /*
     * 角色删除
     */
    public function roleDel($data)
    {
        //删除角色
        $model = new RoleModel(['scenario' => 'delete']);
        if ($model->load($data, '') && $model->validate()) {//验证成功
            $count = $model->deleteAll('id=:id',array(':id'=>$data['id']));
            if($count> 0){
                return parent::getData(1,'operate_success_delete');
            }
        }
        $errorMsg = array_values($model->getErrors());           //报错信息
        return parent::getData(2,$errorMsg[0]);//失败提示
    }

    /*
     * 角色修改
     */
    public function roleUpdate($data)
    {
        //新增角色
        $model = new RoleModel(['scenario' => 'edit']);
        if ($model->load($data, '') && $model->validate()) {//验证成功
            $count = $model->updateAll(array('name'=>$data['name'],'ids'=>$data['ids']),'id=:id',array(':id'=>$data['id']));
            if($count> 0){
                return parent::getData(1,'operate_success_edit');
            }
        }
        $errorMsg = array_values($model->getErrors());           //报错信息
        return parent::getData(2,$errorMsg[0]);//失败提示
    }
}
